import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Client
{
    public static void main(String[] args) 
    {
        try
        {            
            DatagramSocket socket;
            DatagramPacket packet;
            InetAddress addr = InetAddress.getByName("localhost");
            String directory = "C:/Cliente/";
            
            if (args.length == 1) //temos o directorio
            {
                directory = args[0];
            }
            if (args.length != 2) //temos de usar o multicast para saber endereço do servidor
            {                
                socket = new DatagramSocket();
                socket.setSoTimeout(Constants.SOCKET_TIME);
                packet = new DatagramPacket(Constants.REQUEST.getBytes(), Constants.REQUEST.length(), InetAddress.getByName(Constants.UDP_MULTICAST), Constants.UDP_PORT);
                                
                try
                {
                    socket.send(packet);

                    packet.setData(new byte[Constants.DATAGRAM_LENGHT]);
                    packet.setLength(Constants.DATAGRAM_LENGHT);
                    socket.receive(packet);      
                    
                    String msg = new String(packet.getData(),0,packet.getLength());
                    System.out.println(msg);
                    addr = InetAddress.getByName(msg);
                }
                catch(SocketTimeoutException e){}
            }
            else
            {
                directory = args[0];
                addr = InetAddress.getByName(args[1]);
            }
            Socket s = new Socket(addr,Constants.TCP_PORT);

            new ClientGUI(s,directory);
        }
        catch(Exception e){System.out.println("EM CLIENT: " + e);}
    }
}